package controller;

import entity.Book;
import entity.Lending;
import entity.User;
import manager.BookManager;
import manager.LendingManager;
import manager.UserManager;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class LendingController extends SimpleFormController {

    private LendingManager lendingManager;
    private UserManager userManager;
    private BookManager bookManager;

    public LendingController() {
        setCommandClass(Lending.class);
        setCommandName("lendingForm");
    }

    @Override
    protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response, Object command, BindException errors)
            throws Exception {

        Lending lending = (Lending) command;
        User user = userManager.searchUser(Integer.parseInt(lending.getUserId()));
        Book book = bookManager.getBooks(lending.getBookId(), "3");
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("info", lending);
        if (user == null) {
            lending.setResult(": user id is not exist");
        }
        if (book == null) {
            lending.setResult(": book id is not exist");
        } else {
            this.lendingManager.inserNewLending(lending);
            data.put("userName", user.getName());
            data.put("book", book);
            lending.setResult("Successful");
        }
        return new ModelAndView("lendingResult", "lending", data);
    }

    public void setLendingManager(LendingManager lendingManager) {
        this.lendingManager = lendingManager;
    }

    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }

    public void setBookManager(BookManager bookManager) {
        this.bookManager = bookManager;
    }
}
